package com.zyh.service;
import com.zyh.type.CodeStatusEnum;
import com.zyh.dao.UserDao;
import com.zyh.entity.User;
import com.zyh.exception.BusinessException;
import com.zyh.resp.Result;
import com.zyh.utils.Md5Utils;
import com.zyh.utils.TransactionManager;
import java.sql.SQLException;
import java.util.List;

public class UserService {

    private final UserDao userDao = new UserDao();

    public Result<User> login(String username, String password) {

        try {
            TransactionManager.beginTransaction();
            String encryptPwd = Md5Utils.encrypt(password);
            User user = userDao.login(username, encryptPwd);
            if (user == null) {
                throw new BusinessException(CodeStatusEnum.USER_OR_PWD_ERROR);
            }
            TransactionManager.commit();
            return Result.success(user);
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<User> selectById(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(CodeStatusEnum.PARAM_ERROR);
        }
        try {
            TransactionManager.beginTransaction();
            User user = userDao.selectById(userId);
            if (user == null) {
                throw new BusinessException(CodeStatusEnum.USER_NOT_FOUND);
            }
            TransactionManager.commit();
            return Result.success(user);
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<Void> add(User user) {
        try {
            TransactionManager.beginTransaction();
            if (userDao.existsUsername(user.getUsername())) {
                throw new BusinessException(CodeStatusEnum.USER_ALREADY_EXISTS);
            }
            user.setPassword(Md5Utils.encrypt(user.getPassword()));
            userDao.add(user);
            TransactionManager.commit();
            return Result.success();
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<List<User>> selectByPage(int limit, int offset) {
        if (limit <= 0 || offset < 0) {
            throw new BusinessException(CodeStatusEnum.PARAM_ERROR);
        }
        try {
            TransactionManager.beginTransaction();
            List<User> users = userDao.selectByPage(limit, offset);
            TransactionManager.commit();
            return Result.success(users);
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<List<User>> getAll() {
        try {
            TransactionManager.beginTransaction();
            List<User> users = userDao.selectAll();
            TransactionManager.commit();
            return Result.success(users);
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<Void> deleteById(Integer userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(CodeStatusEnum.PARAM_ERROR);
        }
        try {
            TransactionManager.beginTransaction();
            if (userDao.selectById(userId) == null) {
                throw new BusinessException(CodeStatusEnum.USER_NOT_FOUND);
            }
            userDao.deleteById(userId);
            TransactionManager.commit();
            return Result.success();
        } catch (SQLException e) {
            try { TransactionManager.rollback(); } catch (SQLException ex) {}
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try { TransactionManager.release(); } catch (SQLException e) {}
        }
    }

    public Result<Void> updateById(Integer userId, String newEmail) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(CodeStatusEnum.PARAM_ERROR);
        }
        if (newEmail == null || newEmail.trim().isEmpty()) {
            throw new BusinessException(CodeStatusEnum.PARAM_EMPTY);
        }
        try {
            TransactionManager.beginTransaction();
            User user = userDao.selectById(userId);
            if (user == null) {
                throw new BusinessException(CodeStatusEnum.USER_NOT_FOUND);
            }
            userDao.updateById(userId, newEmail);
            TransactionManager.commit();
            return Result.success();
        } catch (SQLException e) {
            try {
                TransactionManager.rollback();
            } catch (SQLException ex) {
                System.err.println("回滚事务失败: " + ex.getMessage());
            }
            throw new BusinessException(CodeStatusEnum.SYSTEM_ERROR);
        } finally {
            try {
                TransactionManager.release();
            } catch (SQLException e) {
                System.err.println("释放数据库连接失败: " + e.getMessage());
            }
        }
    }
}
